import axios from 'axios' //创建一个axios的对象
import router from '@/router/index'
import { Message } from 'element-ui'
const http = axios.create({
    timeout: 60 * 1000 //请求超时
})

// http 请求拦截器
http.interceptors.request.use(
    (config) => {
        let token = localStorage.getItem('token');
        // let token = sessionStorage.getItem('token');
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        localStorage.setItem('expirse', (new Date().getTime() + (1000 * 60 * 60 * 5)))
        return config
    },
    (err) => {
        return Promise.reject(err)
    }
)

// http 响应拦截器
http.interceptors.response.use(
    (response) => {
        // const data = response.data
        if (response.data.code == 401) {
            Message({
                    message: '请重新登录',
                    type: 'error'
                })
                //   throw new Error('请求繁忙，请稍候再试~')
            router.push('/login')
        }
        return response.data;
    },
    (error) => {
        if (error.response) {
            if (error.response.status === 500) {
                Message({
                    message: '请求超时，请稍后重试',
                    type: 'error'
                })
            } else if (error.response.status === 401) {
                Message({
                    message: error.response.data.msg,
                    type: 'error'
                })
            }
        }
        return Promise.reject(error)
    }
)

export default http